package cn.lhz.car.analysis

import cn.lhz.car.util.SparkUtil
import org.apache.spark.sql.{SaveMode, SparkSession}

/**
 * 分析各汽车制造商的销量情况
 *
 * @author 李昊哲
 * @version 1.0.0
 */
object ManufacturerSalesAnalysis {
  def main(args: Array[String]): Unit = {
    // 获取 SparkSession 对象
    val sparkSession: SparkSession = SparkUtil()

    // 读取原始数据
    val df = sparkSession.read
      .option("header", "true")
      .csv("/car-data/ods/Car_sales.csv")

    // 创建临时视图
    df.createOrReplaceTempView("car_sales")

    // 分析各制造商的总销量并排序
    val manufacturerSales = sparkSession.sql(
      """
        |SELECT 
        |  Manufacturer as name,
        |  ROUND(SUM(Sales_in_thousands), 2) as value
        |FROM car_sales
        |GROUP BY Manufacturer
        |ORDER BY value DESC
        |""".stripMargin)

    // 将分析结果保存到Hive
    manufacturerSales.write.mode(SaveMode.Overwrite).saveAsTable("car_sales.dws_manufacturer_sales")

    // 计算各制造商的销量占比
    val manufacturerSalesPercent = sparkSession.sql(
      """
        |WITH total AS (
        |  SELECT SUM(Sales_in_thousands) as total_sales
        |  FROM car_sales
        |)
        |SELECT 
        |  Manufacturer as name,
        |  ROUND(SUM(Sales_in_thousands) / (SELECT total_sales FROM total) * 100, 2) as value
        |FROM car_sales
        |GROUP BY Manufacturer
        |ORDER BY value DESC
        |""".stripMargin)

    // 将分析结果保存到Hive
    manufacturerSalesPercent.write.mode(SaveMode.Overwrite).saveAsTable("car_sales.dws_manufacturer_sales_percent")

    // 释放资源
    sparkSession.stop()
  }
} 